<template>
  <div class="fileImport">
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" :modal="false" :appendToBody="false" width="400px"
               :top="scrollTop" v-dialog-drag :close-on-click-modal="false" @close="closeUpload">
      <el-upload
        ref="upload"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-change="fileChange"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!--          <el-checkbox v-model="upload.updateSupport"/>-->
          <!--          是否更新已经存在的用户数据-->
          <el-link     style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">保 存</el-button>
        <el-button @click="closeUpload">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="批量导入记录" :visible.sync="importForm" :modal="false" :appendToBody="false" width="70%"
               :top="scrollTop" v-dialog-drag :close-on-click-modal="false">
      <el-select v-model="importFormData.sheetName" placeholder="请选择" size="small" style="margin-bottom: 5px"
                 @change="changeImport">
        <el-option
          v-for="item in importChange"
          :key="item"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select>
      <el-table :data="importFormData.data" stripe border>
        <el-table-column label="编码" min-width="150" align="center" prop="code"/>
        <el-table-column label="名称" min-width="150" align="center" prop="name"/>
        <el-table-column label="源字段" min-width="150" align="center" prop="sourceCode">
          <template slot-scope="scope">
            <el-select v-model="scope.row.sourceCode" placeholder="请选择" clearable size="small"
                       style="margin-bottom: 5px" @change="changeSourceCode(scope.row)">
              <el-option
                v-for="(item,index) in importFields"
                :key="index"
                :label="item.name"
                :value="index"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="唯一标识" min-width="200" align="center" prop="id">
          <template slot-scope="scope">
            <el-select v-model="scope.row.uniqueness" clearable placeholder="请选择" size="small"
                       style="margin-bottom: 5px">
              <el-option key="Y" label="是" value="Y"></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importFormBtn">保 存</el-button>
        <el-button @click="importForm = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {getToken} from "@/utils/auth";
  import request from '@/utils/request';
  import {downloadUrl} from 'download.js'

  export default {
    name: "index",
    data() {
      return {
        scrollTop: null,
        // 用户导入参数
        upload: {
          // 是否显示弹出层
          open: false,
          // 弹出层标题
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: null
        },
        //导入弹框
        importForm: false,
        importChange: [],
        importFields: [],
        importFormData: {
          sheetName: null,
          data: [],
        },
        importFile: null,
        url: request.baseURL
      }

    },
    props: ['importData'],
    watch: {
      'importData.open': function () {
        if (this.importData.open) {
          this.upload.title = this.importData.title || "文件导入";
          this.upload.url = this.url + this.importData.url;
        } else {
          this.upload.title = '';
          this.upload.isUploading = false;
          this.upload.url = null;
        }
        this.upload.open = this.importData.open;
        if (this.importData.open) {
          this.$nextTick(() => {
            this.$refs.upload.clearFiles();
          })
        }
      }
    },
    methods: {
      /** 下载模板操作 */
      importTemplate() {
        this.importData.import().then(response => {
          downloadUrl(response.msg,request.baseURL+'/common/download?fileName=' +response.msg +'&delete=true')
          // this.download(response.msg);
        });
      },
      // 文件状态改变时的钩子
     fileChange(file, fileList) {
        if (fileList.length > 1) {
          fileList.splice(0, 1);
        }
        this.fileData.name = fileList[0].name
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.importFormData.sheetName = [];
        // this.$refs.upload.clearFiles();
        this.importChange = response.sheetNames;
        this.importFormData.sheetName = this.importChange[0];
        this.changeImport();
        // this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
        // this.getList();
      },
      changeImport() {
        request({
          url: this.importData.importParamUrl,
          method: 'post',
          params: {
            sheetName: this.importFormData.sheetName,
          }
        }).then(res => {
          this.importFormData.data = [];
          var list = this.importData.codeList;
          for (let i = 0; i < list.length; i++) {
            var obj = {};
            var isShow = true;
            for (let j = 0; j < res.params.length; j++) {
              if (list[i].name == res.params[j].name) {
                obj = {code: list[i].code, name: list[i].name, sourceCode: j, uniqueness: null};
                isShow = false;
              }
            }
            if (isShow) {
              obj = {code: list[i].code, name: list[i].name, sourceCode: null, uniqueness: null};
            }
            this.importFormData.data.push(obj)
          }
          this.$parent.importData.open = false;
          this.upload.isUploading = false;
          this.importForm = true;
          this.importFields = res.params;
        }).catch(err => {

        })
      },
      changeSourceCode(row) {
        var data = this.importFormData.data
        for (let i = 0; i < data.length; i++) {
          if (data[i].sourceCode == row.sourceCode && data[i].code != row.code) {
            data[i].sourceCode = null;
          }
        }
      },
      importFormBtn() {
        const loading = this.$loading({
          lock: true,
          text: '正在导入，请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        request({
          url: this.importData.importUrl,
          method: 'post',
          data: this.importFormData
        }).then(res => {
          this.importForm = false
          this.$alert(res.msg, "导入结果", {dangerouslyUseHTMLString: true});
          this.$parent.getList();
          loading.close();
        }).catch(err => {
          this.$alert(err, "导入结果", {dangerouslyUseHTMLString: true});
          loading.close();
        })
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      closeUpload(){
        this.$parent.importData.open = false;
      }
    },
    mounted() {
      this.utils.mounteds(this);
    },
    destroyed() {
      this.utils.destroyeds(this);
    }
  }
</script>

<style scoped>

</style>
